<template>
  <div class="box-container">
    <!-- 搜索 -->
      <div class="top-main">
    <el-form class="top-form-fl" :model="queryParams" ref="queryRef" label-width="auto" :inline="true">
      <el-form-item label="菜单名称:" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入菜单名称" clearable/>
      </el-form-item>
      <el-form-item label="创建日期:" prop="createStartTime" style="width: 400px;">
        <el-col :span="11">
          <el-date-picker v-model="queryParams.createStartTime" type="date" placeholder="开始日期" style="width: 100%" />
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-date-picker v-model="queryParams.createEndTime" type="date" placeholder="结束日期" style="width: 100%" />
        </el-col>
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
          <el-button class="top-Search" @click="getFilterData" type="primary">搜索</el-button>
          <el-button class="top-Refresh" @click="resetFrome">重置</el-button>
      </div>   
      </div>
    <el-button type="primary" :icon="Plus" style="float:right;margin: 20px;"
      @click="addPermissionRoleDialog(1)">新增</el-button>

    <div style="padding: 0 10px;">
       <el-table
         v-if="refreshTable"
         :data="tableData.data"
         row-key="id"       
         :default-expand-all="isExpandAll"
         :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
         <el-table-column prop="name" label="菜单名称" :show-overflow-tooltip="true"></el-table-column>
         <el-table-column label="菜单类型" align="center">
            <template #default="scope">
               <div v-if="scope.row.type==1">菜单</div>
               <div v-else-if="scope.row.type==2">目录</div>
               <div v-else-if="scope.row.type==3">外链</div>
               <div v-else-if="scope.row.type==4">按钮</div>
            </template>
         </el-table-column>
         <el-table-column prop="component" align="center" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
         <el-table-column prop="path" align="center" label="path" :show-overflow-tooltip="true"></el-table-column>
         <el-table-column prop="companyRole" align="center" label="标识" :show-overflow-tooltip="true"></el-table-column>
         <el-table-column prop="icon" label="图标" align="center">
            <template #default="scope">
               <svg-icon :icon-class="scope.row.icon" />
            </template>
         </el-table-column>
         <el-table-column prop="sort" align="center" label="排序"></el-table-column>
         <el-table-column label="是否隐藏" align="center">
            <template #default="scope">
               <div>{{scope.row.hidden == 0 ? '否':'是'}}</div>
            </template>
         </el-table-column>
          <el-table-column label="状态" align="center">
            <template #default="scope">
               <div>{{scope.row.visible == 1 ? '启用':'关闭'}}</div>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
               <el-button link type="primary" icon="Plus" @click="addPermissionRoleDialog(2,scope.row)">新增</el-button>
               <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
         </el-table-column>
      </el-table>
    </div>
    <!-- 新增编辑弹窗 -->
    <el-dialog v-model="dialogUserRole" :title="typeOpen==1 ? '新增菜单':'编辑菜单'" @close="cancel" width="600px">
      <el-form :model="form" :rules="rules" ref="menuRef" label-width="80px">
                  <el-form-item label="上级菜单" prop="parentId">
                    <el-tree-select
                        v-model="form.parentId"
                        :data="menuOptions"
                        :props="{ value: 'id', label: 'name', children: 'children' }"
                        value-key="id"
                        placeholder="选择上级菜单"
                        check-strictly
                     />        
                  </el-form-item>
                  <el-form-item label="菜单类型" prop="type">
                     <el-radio-group v-model="form.type">
                        <el-radio :value="1">菜单</el-radio>
                        <el-radio :value="2">目录</el-radio>
                        <el-radio :value="3">外链</el-radio>
                        <el-radio :value="4">按钮</el-radio>
                     </el-radio-group>
                  </el-form-item>
                  <el-form-item label="菜单名称" prop="name">
                     <el-input v-model="form.name" placeholder="请输入菜单名称" maxlength="20" />
                  </el-form-item>
                  <el-form-item label="name" prop="code">
                     <el-input v-model="form.code" placeholder="请输入name" maxlength="50" />
                  </el-form-item>
                  <el-form-item label="path" prop="path">
                     <el-input v-model="form.path" placeholder="请输入path" maxlength="100" />
                  </el-form-item>
                   <el-form-item label="路径" prop="component">
                     <el-input v-model="form.component" placeholder="请输入路径" maxlength="100" />
                  </el-form-item>
                   <!-- <el-form-item label="路径" prop="component" v-if="form.type==1">
                     <el-input v-model="form.component" placeholder="请输入路径" maxlength="50" />
                  </el-form-item> -->
                  <el-form-item label="标识" prop="companyRole">
                     <el-input v-model="form.companyRole" placeholder="请输入标识" maxlength="50" />
                  </el-form-item>
                  <el-form-item label="菜单图标" prop="icon">
                     <el-popover
                        placement="bottom-start"
                        :width="540"
                        trigger="click"
                     >
                        <template #reference>
                           <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" readonly>
                              <template #prefix>
                                 <svg-icon
                                    v-if="form.icon"
                                    :icon-class="form.icon"
                                    class="el-input__icon"
                                    style="height: 32px;width: 16px;"
                                 />
                                 <el-icon v-else style="height: 32px;width: 16px;"><search /></el-icon>
                              </template>
                           </el-input>
                        </template>
                        <icon-select ref="iconSelectRef" @selected="selected" :active-icon="form.icon" />
                     </el-popover>
                  </el-form-item>
                  <el-form-item label="标签" prop="tags">
                     <el-input v-model="form.tags" placeholder="请输入标签" maxlength="30" />
                  </el-form-item>
                  <el-form-item label="权限" prop="perm">
                     <el-input v-model="form.perm" placeholder="请输入权限" maxlength="20" />
                  </el-form-item>
                   <el-form-item label="是否隐藏" prop="hidden">
                     <el-radio-group v-model="form.hidden">
                        <el-radio :value="1">是</el-radio>
                        <el-radio :value="0">否</el-radio>
                     </el-radio-group>
                  </el-form-item>
                   <el-form-item label="显示状态" prop="visible">
                     <el-radio-group v-model="form.visible">
                        <el-radio :value="1">启用</el-radio>
                        <el-radio :value="0">关闭</el-radio>
                     </el-radio-group>
                  </el-form-item>
                  <el-form-item label="排序" prop="sort">
                     <el-input v-model="form.sort" placeholder="请输入排序" maxlength="20" />
                  </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm(menuRef)">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import Table from '@/views/components/table/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import { getRolesPage, deleteRole, updateRoleStatus, addMenus,updateMenus, getRoleDetailById, } from '@/api/systemManage/menu/index'
import { handleTree } from '@/utils/ruoyi'
import IconSelect from "@/components/IconSelect";
// const { proxy } = getCurrentInstance();
import type { FormInstance, FormRules } from 'element-plus'
// 联级选择器 默认全部展开（官方不支持默认全部展开 需相应方法协作展开）
const menuRef=ref()
const queryRef=ref(null)
const dialogUserRole=ref(false) //弹框
const isExpandAll = ref(false);
const refreshTable = ref(true);
const iconSelectRef = ref(null);
const data = reactive({
  form: {
    parentId:0,
    type:1,
    name:'',
    code:'',
    path:'',
    component:'',
    companyRole:'',
    redirect:'',
    icon:'',
    sort:'',
    tags:[],
    perm:'',
    visible:1,
    keepAlive:0,
    alwaysShow:1,
    hidden:0,
  },
  queryParams: {
    name:'',
    createStartTime:'',
    createEndTime:'',
    sortBeans:[{
      field: "sort",
      isAsc: "asc",
    }]
  },
  rules: {
    type: [{ required: true, message: "菜单类型不能为空", trigger: "blur" }],
    name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
    code: [{ required: true, message: "name不能为空", trigger: "blur" }],
    path: [{ required: true, message: "path不能为空", trigger: "blur" }],
    component: [{ required: true, message: "路径不能为空", trigger: "blur" }],
    companyRole: [{ required: true, message: "标识不能为空", trigger: "blur" }],
    sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
  }
});
const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  // getPermission()
  getFilterData()

})

// 基础数据
const tableData = reactive({
  header: [
    { key: 'username', colWidth: '60', title: '菜单名称', type: 'name', isCheck: true },
    { key: 'nickname', colWidth: '60', title: '链接地址', type: 'name', isCheck: true },
    { key: 'roleNames', colWidth: '60', title: '父级菜单', type: 'name', isCheck: true },
    { key: 'userType', colWidth: '60', title: '菜单类型', type: 'name', isCheck: true },
    { key: 'mobile', colWidth: '60', title: '图标', type: 'name', isCheck: true },
    { key: 'email', colWidth: '60', title: '排序', type: 'name', isCheck: true },
    { key: 'status', colWidth: '40', title: '状态', type: 'status', isCheck: true },
    { key: 'createTime', colWidth: '80', title: '注册日期', type: 'createTime', isCheck: true },
    {
      key: 'operate',
      colWidth: '60',
      title: '操作',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: 'Edit',
          type: 0,  //企业用户 1  企业账号 0 
          status: "1",
          command: 'editPermissions',
          content: '',
        },
        {
          icon: 'Open',
          type: 0,  //企业用户 1  企业账号 0 
          status: "1",
          command: 'handleSwitch',
          content: '',
        },
        {
          icon: 'Delete',
          type: 0,  //企业用户 1  企业账号 0 
          command: 'deleteBox',
          content: '',
        }
      ]
    }
  ],
  data: [],
  config: {
    isSelection: false,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 总条数
    loading: false,
    isRealName: false, // 是否已经实名认证
  }
})
// 重置搜索数据
const resetFrome = () => {
  queryRef.value.resetFields()
  queryRef.value.createStartTime=''
  queryRef.value.createEndTime=''
  getFilterData()
}
// 搜索数据
const getFilterData = () => {
  getRolesPage(JSON.stringify(queryParams.value)).then(res => {
        tableData.data  = handleTree( res.data, "id");
  })
}
const menuOptions=ref([])
/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
  let data={
    sortBeans:[{
        field: "sort",
        isAsc: "asc",
      }]
  }
  getRolesPage(JSON.stringify(data)).then(response => {
    const menu = { id: 0, name: "主类目", children: [] };
    menu.children = handleTree(response.data, "id");
    menuOptions.value.push(menu);
  });
}
/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
}
/** 选择图标 */
function selected(name) {
  form.value.icon = name;
}
/** 提交按钮 */
const submitForm = (formEl: FormInstance | undefined) =>{
  if (!formEl) return
  formEl.validate(valid => {

   let dataForm=JSON.parse(JSON.stringify(form.value))
  //  if(dataForm.type!=1){
  //   dataForm.component='Layout'
  //  }
  dataForm.tags=JSON.stringify(dataForm.tags)
    if (valid) {
      if (form.value.id != undefined) {
        updateMenus(dataForm).then(response => {
          cancel();
          getFilterData()
        });
      } else {
        addMenus(dataForm).then(response => {
          cancel();
          getFilterData()
      
        });
      }
    }
  });
};
//关闭弹框
const cancel = () => {
  typeOpen.value=1
  dialogUserRole.value=false
  delete form.value.id
  form.value.component=''
  menuRef.value.resetFields()// 重置数据
}
const typeOpen=ref(1) //1新增 2编辑
// 新增弹窗
const addPermissionRoleDialog = (type,row) => {
  typeOpen.value=1
  dialogUserRole.value=true
  if(type==2){
    form.value.parentId=row.id
  } 
  getTreeselect()
}

// 编辑
const handleUpdate = (row) => {
  typeOpen.value=2
  dialogUserRole.value=true
  getRoleDetail(row.id)
}
//详情查询
const getRoleDetail=(id)=>{
  getRoleDetailById(id).then(res => {
    form.value=res.data
    form.value.tags=JSON.parse(res.data.tags)
    getTreeselect()
  })
}
//删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该条数据吗？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteRole(row.id).then((res) => {
        ElMessage.success('删除成功')
        getFilterData()
      })
    })
}
// 切换状态 updateRoleStatus
const handleSwitch = (row, statu) => {
  console.log(row, statu)
  let messTitle = ''
  if (statu == '1') {
    messTitle = '该权限即将启用？'
  } else if (statu == '0') {
    messTitle = '该权限即将停用？'
  }
  ElMessageBox.confirm(
    messTitle,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      updateRoleStatus(row, statu).then(res => {
        console.log(res)
        getFilterData()
        ElMessage.success('状态修改成功')
      }).catch(error => {
        ElMessage.warning('状态修改失败')
      })
    })


}

</script>

<style scoped>
 .box-container{
    padding: 20px;
}
.choose-item-2 {
  margin-left: 20px;
}
.stust{
  padding:0 20px;
}
.choose-item-3 {
  display: block;
  margin-left: 20px;
}
</style>